package org.sao.security.app.code.impl;

import java.util.concurrent.TimeUnit;

import javax.validation.ValidationException;

import org.apache.commons.lang.StringUtils;
import org.sao.security.core.validate.code.ValidateCodeRepository;
import org.sao.security.core.validate.code.ValidateCodeType;
import org.sao.security.core.validate.code.sms.ValidateCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;


@Component
public class RedisValidateCodeRepository implements ValidateCodeRepository {
	
	
	@Autowired
	private RedisTemplate redisTemplate;
	
	/**
	 * key
	 */
	 String REDIS_KEY="REDIS_KEY_FOR_CODE_";
	 
	 String APPID="appid";
	
	@Override
	public void save(ServletWebRequest request, ValidateCode validateCode,ValidateCodeType type) {
		// TODO Auto-generated method stub
		System.out.println("构建验证码放入redis时的key:"+type.toString().toUpperCase());
		System.out.println("save:"+getRedisKey(request,type));
		ValueOperations<String, ValidateCode> operations=redisTemplate.opsForValue();	
	    operations.set(getRedisKey(request,type), validateCode,30,TimeUnit.MINUTES);
        
	}

	@Override
	public ValidateCode get(ServletWebRequest request,ValidateCodeType type) {
		// TODO Auto-generated method stub
		ValueOperations<String, ValidateCode> operations=redisTemplate.opsForValue();
		ValidateCode validateCode=operations.get(getRedisKey(request,type));	
		System.out.println("get:"+getRedisKey(request,type));
		System.out.println(validateCode);
		return validateCode;
	}

	@Override
	public void remove(ServletWebRequest request,ValidateCodeType type) {
		// TODO Auto-generated method stub
		System.out.println("remove:"+getRedisKey(request,type));
		redisTemplate.delete(getRedisKey(request,type));
	}
	
	/**
	 * 构建验证码放入session时的key
	 * 
	 * @param request
	 * @return
	 */
	private String getRedisKey(ServletWebRequest request,ValidateCodeType type) {
		String appid=request.getHeader(APPID);
		if(StringUtils.isBlank(appid)) {
			throw new ValidationException("appid不能为空");
		}
		return REDIS_KEY + type.toString().toUpperCase()+"_"+appid.toUpperCase();
	}

	

}
